﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text;

namespace Invest.DataBaseUpdater.Core
{
    public class BaseProcessor : IDisposable
    {

        internal SqlConnection Connection;

        public BaseProcessor(SqlConnection connection)
        {
            Connection = connection;
        }

        internal void OpenConnection()
        {
            if (Connection.State != ConnectionState.Closed)
            {
                Connection.Close();
            }
            Connection.Open();
        }

        public void Dispose()
        {
            if (Connection.State == ConnectionState.Open)
                Connection.Close();
        }

        internal IEnumerable<string> GetListExecutedFiles()
        {
            const string query = "SELECT [file-name] FROM  [System].[RefactorLog]";
            var command = new SqlCommand(query, Connection);
            var reader = command.ExecuteReader();
            var files = new List<string>();
            while (reader.Read())
            {
                files.Add(reader[0].ToString());
            }

            return files;
        }

        internal void ReadSqlFromFile(string scriptFile, out string sqlQuery, out string sqlHeader, out bool skipTransaction)
        {
            var sqlQueryBuilder = new StringBuilder();
            var sqlHeaderBuilder = new StringBuilder();
            skipTransaction = false;
            string line;
            var streamReader = new StreamReader(scriptFile);
            while ((line = streamReader.ReadLine()) != null)
            {
                if (line.ToString(CultureInfo.InvariantCulture).Contains("--HEADER"))
                {
                    var header = line.ToString(CultureInfo.InvariantCulture).Replace("--HEADER", "");
                    sqlHeaderBuilder.AppendLine(header);
                }
                else
                {
                    if (line.ToString(CultureInfo.InvariantCulture).Contains("--SKIPTRANSACTION"))
                    {
                        skipTransaction = true;
                    }
                    else
                    {
                        sqlQueryBuilder.AppendLine(line.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }

            streamReader.Close();
            sqlHeader = sqlHeaderBuilder.ToString().Trim();
            sqlQuery = sqlQueryBuilder.ToString().Trim();
        }



    }
}
